package ace.cmp.spring.data.jdbc.querydsl.core.dml;

import com.querydsl.core.types.Path;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.dml.AbstractMapper;
import com.querydsl.sql.dml.Mapper;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;

/**
 * @author caspar
 * @date 2024/7/1 17:43 添加扩展过滤
 */
public class QuerydslMapper extends AbstractMapper<Object> {
  private final Mapper<Object> parentMapper;
  private final Set<String> ignoreFieldNames;

  public QuerydslMapper(Mapper<Object> parentMapper, Set<String> ignoreFieldNames) {
    Assert.notNull(parentMapper, "parentMapper can not be null");
    this.ignoreFieldNames =
        CollectionUtils.isEmpty(ignoreFieldNames) ? new HashSet<>() : ignoreFieldNames;
    this.parentMapper = parentMapper;
  }

  @Override
  public Map<Path<?>, Object> createMap(RelationalPath<?> path, Object object) {
    return this.parentMapper.createMap(path, object).entrySet().stream()
        .filter(p -> this.filterIgnoreField(p, object))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
  }

  private boolean filterIgnoreField(Map.Entry<Path<?>, Object> entry, Object object) {
    if (CollectionUtils.isEmpty(ignoreFieldNames)) {
      return true;
    }
    return !this.ignoreFieldNames.contains(entry.getKey().getMetadata().getName());
  }
}
